// ==UserScript==
// @name           Popmundo Locales For Sale Search Criteria
// @namespace      Scriptmundo
// @include        http://www*.popmundo.com/Common/Company.asp*
//@description When you buy a new local decide when to buy and how much you want to spend!
// @version 0.8
// ==/UserScript==

function xpathNode(xpath) {
	return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

function xpathNodes(xpath) {
	return document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
}

var SALES_FORM_XPATH = "/html/body/table[3]/tbody/tr/td[1]/table[2]/tbody/tr/td/form";
var SALES_ROWS_XPATH = "/html/body/table[3]/tbody/tr/td[1]/table[2]/tbody/tr/td/table[1]/tbody/tr[position() > 1]";
var HIDDEN_SALE_XPATH = "/html/body/table[3]/tbody/tr/td[1]/table[2]/tbody/tr/td/form/input[@name='action' and @value='LocalesForSale']";

if (location.href.toLowerCase().indexOf("action=localesforsale") > 0)
	var isSalePage = true;
	
if (!isSalePage) {
	var hiddenNode = xpathNodes(HIDDEN_SALE_XPATH);
	if (hiddenNode.snapshotLength >= 1)
		var isSalePage = true
}

if (!isSalePage)
	return;

var form = xpathNode(SALES_FORM_XPATH);

var newForm = document.createElement('form');
newForm.setAttribute('action', '#');
newForm.setAttribute('onsubmit', 'return false;');
newForm.appendChild(document.createTextNode("Max Price: "));

var maxPrice = document.createElement('input');
maxPrice.setAttribute('type', 'text');
maxPrice.setAttribute('id', 'maxPrice');
maxPrice.setAttribute('size', 15);
maxPrice.addEventListener('keyup', criteriaOnChange, false);
newForm.appendChild(maxPrice);
// newForm.appendChild(document.createElement('br'));
// newForm.appendChild(document.createElement('br'));

var maxDay = document.createElement('select');
maxDay.setAttribute('id', 'maxDay');
//maxDay.setAttribute('style', 'position: relative; left: 30px');
maxDay.addEventListener('change', criteriaOnChange, false);
// newForm.appendChild(document.createTextNode(" Before: "));

var minDay = document.createElement('select');
minDay.setAttribute('id', 'minDay');
minDay.addEventListener('change', criteriaOnChange, false);
// newForm.appendChild(document.createTextNode(" After: "));

var startDate = new Date();
//startDate = startDate.getTime;
var dayMillisec = 1 * 1000 * 60 * 60 * 24;

for (var days = 0; days <= 7; days++) {
	var optionDate = new Date();
	optionDate.setTime(startDate.getTime() + (dayMillisec * days));
	
	var optionDay = optionDate.getDate();
	//GM_log(optionDay);
	if (optionDay < 10)
		optionDay = '' + 0 + optionDay;
	
	var optionMon = optionDate.getMonth() + 1;
	if (optionMon < 10)
		optionMon = '' + 0 + optionMon;
		
	var optionYear = optionDate.getFullYear();
	
	var maxDayOption = document.createElement('option');
	maxDayOption.appendChild(document.createTextNode(optionDay + "/" + optionMon + "/" + optionYear))
	optionDate.setHours(23,59,59,999);
	maxDayOption.setAttribute('value', optionDate.getTime());
	
	var minDayOption = document.createElement('option');
	minDayOption.appendChild(document.createTextNode(optionDay + "/" + optionMon + "/" + optionYear))
	optionDate.setHours(0,0,0,1);
	minDayOption.setAttribute('value', optionDate.getTime());
	
	if (days == 0)
		minDayOption.setAttribute('selected', 'selected');
	
	if (days == 7)
		maxDayOption.setAttribute('selected', 'selected');
	
	maxDay.appendChild(maxDayOption);
	minDay.appendChild(minDayOption);
	
}

newForm.appendChild(document.createTextNode(" From: "));
newForm.appendChild(minDay);
newForm.appendChild(document.createTextNode(" Till: "));
newForm.appendChild(maxDay);

form.parentNode.insertBefore(newForm, form.nextSibling);


function criteriaOnChange (event) {
	var target = event ? event.target : this;
	//var key = event.which;
	
	//GM_log(target.value.replace(/[^0-9]/g, ""));
	var maxPrice = parseInt(document.getElementById('maxPrice').value.replace(/[^0-9]/g, ""));
	if (!isNaN(maxPrice))
		target.value = maxPrice;
	else {
		target.value = '';
		maxPrice = -1;
	}
	
	// if (maxPrice.toString().length == 0)
		// maxPrice = 900000000;
	//alert(maxPrice);
	
	var maxDay = new Date();
	maxDay.setTime(document.getElementById('maxDay').value);
	
	var minDay = new Date();
	minDay.setTime(document.getElementById('minDay').value);
	//alert(date);
	
	var salesRows = xpathNodes(SALES_ROWS_XPATH);
	
	for (var i = 0; i < salesRows.snapshotLength; i++) {	
		saleRow = salesRows.snapshotItem(i);
		
		var priceCells = saleRow.getElementsByTagName('td');
		var price = parseInt(priceCells[2].innerHTML.replace(/&nbsp;/g,""));
		
		var isPriceOk = false;
		if (price <= maxPrice || maxPrice == -1)
			var isPriceOk = true;
		
		var endDate = saleRow.title.match(/([\d]{1,2})\/([\d]{1,2})\/([\d]{2,4})/);
		
		if (endDate[1].indexOf("0") == 0)
			endDate[1] = endDate[1].substr(1);
		var dayBefore = parseInt(endDate[1]);
		
		if (endDate[2].indexOf("0") == 0)
			endDate[2] = endDate[2].substr(1);
		var monBefore = parseInt(endDate[2]) - 1;
		
		var yearBefore = endDate[3];
				
		//GM_log(saleRow.title + ': ' + dayBefore + '-' + monBefore + '-' + yearBefore);		
		
		var endDate = new Date();
		endDate.setDate(dayBefore);
		endDate.setMonth(monBefore);
		endDate.setFullYear(yearBefore);
		endDate.setHours(23,59,59,999);
		//GM_log(endDate + ' ------------------- ' + maxDay);
		//GM_log(endDate + ' ------------------- ' + minDay);
		
		var isMaxDateOk = false;		
		if (endDate.getTime() <= maxDay.getTime())
			var isMaxDateOk = true;
		
		var isMinDateOk = false;		
		if (endDate.getTime() >= minDay.getTime())
			var isMinDateOk = true;
		
		if (isPriceOk && isMaxDateOk && isMinDateOk)
			saleRow.style.display = 'table-row';
		else
			saleRow.style.display = 'none';
		
		//GM_log(price);
		
	}
}